import 'package:flutter/material.dart';
import 'navigator/hi_navigator.dart';
import 'http/dao/login_dao.dart';
import 'model/home_mo.dart';
import 'http/core/hi_net.dart';
import 'http/core/hi_error.dart';
import 'db/hi_cache.dart';
import 'util/color.dart';
import 'page/registration_page.dart';
import 'page/login_page.dart';
import 'page/home_page.dart';
import 'page/video_detail_page.dart';
import 'navigator/bottom_navigator.dart';
import 'model/video_model.dart';

void main() {
    runApp(BliliApp());
}

class BliliApp extends StatefulWidget {
    @override
    _BliliAppState createState() => _BliliAppState();
}

class _BliliAppState extends State<BliliApp> {
    BiliRouteDelegate _routeDelegate = BiliRouteDelegate();

    @override
    Widget build(BuildContext context){
        return FutureBuilder<HiCache>(
            //初始化
            future: HiCache.preInit(),
            builder: (BuildContext context,AsyncSnapshot<HiCache> snapshot){
                var widget = snapshot.connectionState == ConnectionState.done ? (
                    Router(routerDelegate: _routeDelegate)
                ) : (
                    Scaffold(
                        body: Center(
                            child: CircularProgressIndicator(),
                        ),
                    )
                );

                return MaterialApp(
                    home: widget,
                    theme: ThemeData(primarySwatch: white),
                );
            }
        );
    }
}

//===============路由
class BiliRouteDelegate extends RouterDelegate<BiliRoutePath> with ChangeNotifier,PopNavigatorRouterDelegateMixin<BiliRoutePath> {
    final GlobalKey<NavigatorState> navigatorKey;
    BiliRouteDelegate() : navigatorKey = GlobalKey<NavigatorState>() {
        HiNavigator.getInstance().registerRouteJump(RouteJumpListener(onJumpTo: (RouteStatus routeStatus,{Map args}){
            _routeStatus = routeStatus;
            if(routeStatus == RouteStatus.detail){
                this.videoModel = args["videoMo"];
            }
            notifyListeners();
        }));
        //设置网络错误拦截器
        HiNet.getInstance().setErrorInterceptor((error) {
            if (error is NeedLogin) {
                //清空失效的登录令牌
                HiCache.getInstance().setString(LoginDao.BOARDING_PASS, null);
                //拉起登录
                HiNavigator.getInstance().onJumpTo(RouteStatus.login);
            }
        });
    }

    RouteStatus _routeStatus = RouteStatus.home;
    List<MaterialPage> pages = [];
    VideoModel videoModel;

    @override
    Widget build(BuildContext context){
        var index = getPageIndex(pages, routeStatus);
        List<MaterialPage> tempPages = pages;
        //管理堆栈路由
        if(index != -1){
            //要打开的页面在盏中已存在，则将该页面和它上面的所有页面进行出盏
            tempPages = tempPages.sublist(0,index);
        }

        var page;
        if(routeStatus == RouteStatus.home){
            //跳转首页时将盏中其他页面进行出盏，因为首页不可回退
            pages.clear();
            page = pageWrap(BottomNavigator());
        } else if(routeStatus == RouteStatus.detail) {
            page = pageWrap(VideoDetailPage(videoModel));
        } else if(routeStatus == RouteStatus.registration) {
            page = pageWrap(RegistrationPage());
        } else if(routeStatus == RouteStatus.login) {
            page = pageWrap(LoginPage());
        }

        tempPages = [...tempPages,page];
        //通知路由发生变化
        HiNavigator.getInstance().notify(tempPages, pages);
        pages = tempPages;

		return WillPopScope(
			onWillPop: () async => !await navigatorKey.currentState.maybePop(),
			child: Navigator(
				key: navigatorKey,
				pages: pages,
				onPopPage: (route,result){
					if(route.settings is MaterialPage){
						//登录页未登录返回拦截
						if((route.settings as MaterialPage).child is LoginPage){
							if(!hasLogin){
								print("请先登录");
								return false;
							}
						}
					}
					//执行返回操作
					if(!route.didPop(result)){
						return false;
					}

					var tempPages = [...pages];
					pages.removeLast();
					//通知路由变化
                    HiNavigator.getInstance().notify(pages, tempPages);
					return true;
				},
			)
		);
    }

    RouteStatus get routeStatus {
        if(_routeStatus != RouteStatus.registration && !hasLogin){
            return _routeStatus = RouteStatus.login;
        } else if(videoModel != null) {
            return _routeStatus = RouteStatus.detail;
        } else {
            return _routeStatus;
        }
    }

    bool get hasLogin => LoginDao.getBoardingPass() != null;

    @override
    Future<void> setNewRoutePath(BiliRoutePath path) async { }
}


class BiliRoutePath {
    final String location;

    BiliRoutePath.home()    : location    = "/";
    BiliRoutePath.detail () : location    = "/detail";
}

//创建页面
pageWrap(Widget child){
    return MaterialPage(
        key: ValueKey(child.hashCode),
        child:child
    );
}